<template>
  <div>
    <el-card>
      <template #header><h2>入住登记</h2></template>

      <!-- 搜索区域 -->
      <el-form :model="searchForm" inline>
        <el-form-item>
          <el-input
            v-model="searchForm.name"
            placeholder="姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="老人类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" style="width: 160px">
            <el-option label="自理老人" :value="1" />
            <el-option label="护理老人" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchData" :icon="Search">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addData">
            登记<el-icon><Upload /></el-icon>
          </el-button>
        </el-form-item>
      </el-form>

      <div class="table-title"><h3>客户信息</h3></div>

      <!-- 表格区域 -->
      <el-table :data="tableData" border stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="60"/>
        <el-table-column prop="name" label="姓名" width="120"/>
        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            {{ row.type === 1 ? '自理老人' : '护理老人' }}
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80" 
          :formatter="r => r.gender===0?'男':'女'"/>
        <el-table-column prop="age" label="年龄" width="80"/>
        <el-table-column prop="birthDate" label="出生日期" width="120"/>
        <el-table-column prop="idCardNumber" label="身份证号" width="180"/>
        <el-table-column label="血型" width="100">
          <template #default="{ row }">{{ bloodTypeMap[row.bloodType] }}</template>
        </el-table-column>
        <el-table-column prop="familyContact" label="家属" width="120"/>
        <el-table-column prop="building" label="楼栋" width="80"/>
        <el-table-column prop="roomNumber" label="房间号" width="100"/>
        <el-table-column prop="bedNumber" label="床位号" width="100"/>
        <el-table-column prop="checkInTime" label="入住时间" width="150"/>
        <el-table-column prop="contractEndTime" label="合同到期" width="150"/>
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="{ row }">
            <el-button type="danger" size="small" @click="deleteData(row.id)">
              <el-icon><Delete /></el-icon> 删除
            </el-button>
            <el-button type="primary" size="small" @click="editData(row)">
              <el-icon><Edit /></el-icon> 修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[2,3,5,7]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="loadData"
        @size-change="loadData"
      />
    </el-card>

    <!-- 抽屉表单 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="60%">
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>

        <!-- 类型固定，不可修改 -->
        <el-form-item label="类型" prop="type">
          <el-select v-model="formData.type" disabled>
            <el-option label="自理老人" :value="1" />
            <el-option label="护理老人" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker v-model="formData.birthDate" type="date" placeholder="出生日期"/>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="formData.age" disabled />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="formData.gender">
            <el-radio :value="0">男</el-radio>
            <el-radio :value="1">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCardNumber">
          <el-input v-model="formData.idCardNumber" />
        </el-form-item>

        <!-- 血型 下拉 -->
        <el-form-item label="血型" prop="bloodType">
          <el-select v-model="formData.bloodType" placeholder="请选择血型">
            <el-option label="A 型" :value="1" />
            <el-option label="B 型" :value="2" />
            <el-option label="AB 型" :value="3" />
            <el-option label="O 型" :value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="家属" prop="familyContact">
          <el-input v-model="formData.familyContact" />
        </el-form-item>

        <el-form-item label="楼栋" prop="building">
          <el-input v-model="formData.building" disabled />
        </el-form-item>

        <el-form-item label="房间号" prop="roomNumber">
          <el-select v-model="formData.roomNumber" placeholder="选择房间" @change="onRoomChange">
            <el-option v-for="room in rooms" :key="room" :label="room" :value="room" />
          </el-select>
        </el-form-item>

        <el-form-item label="床位号" prop="bedNumber">
          <el-select v-model="formData.bedNumber" placeholder="选择床位">
            <el-option v-for="bed in bedData" :key="bed" :label="bed" :value="bed" />
          </el-select>
        </el-form-item>

        <el-form-item label="入住时间" prop="checkInTime">
          <el-date-picker v-model="formData.checkInTime" type="datetime" placeholder="入住时间"/>
        </el-form-item>

        <el-form-item label="合同到期" prop="contractEndTime">
          <el-date-picker v-model="formData.contractEndTime" type="datetime" placeholder="合同到期"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">{{ drawerTitle }}</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, watch, inject } from 'vue'
import qs from 'qs'
import { Search, Upload, Delete, Edit } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const axios = inject('axios')

// 状态映射
const bloodTypeMap = { 1: 'A 型', 2: 'B 型', 3: 'AB 型', 4: 'O 型' }

// 搜索条件
const searchForm = reactive({ name: '', type: 1 })
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 抽屉状态
const drawerVisible = ref(false)
const drawerTitle = ref('')
const formRef = ref(null)

// 表单
const formData = reactive({
  id: 0,
  name: '',
  type: 1,
  birthDate: '',
  age: 0,
  gender: 0,
  idCardNumber: '',
  bloodType: 1,
  familyContact: '',
  building: '606',
  roomNumber: '',
  bedNumber: '',
  checkInTime: '',
  contractEndTime: '',
  isDeleted: false
})

// 房间 & 床位
const rooms = ref([])
const bedData = ref([])

// 验证
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  birthDate: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  idCardNumber: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
  bloodType: [{ required: true, message: '请选择血型', trigger: 'change' }],
  familyContact: [{ required: true, message: '请输入家属', trigger: 'blur' }],
  roomNumber: [{ required: true, message: '请选择房间号', trigger: 'change' }],
  bedNumber: [{ required: true, message: '请选择床位号', trigger: 'change' }],
  checkInTime: [{ required: true, message: '请选择入住时间', trigger: 'change' }],
  contractEndTime: [
    { required: true, message: '请选择合同到期', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        const toTime = val => val instanceof Date ? val.getTime() : new Date(val).getTime();
        if (!value || !formData.checkInTime) return callback();
        if (toTime(value) >= toTime(formData.checkInTime)) {
          callback();
        } else {
          callback(new Error('合同到期不能早于入住时间'));
        }
      },
      trigger: 'change'
    }
  ]
}

// 自动计算年龄
watch(() => formData.birthDate, date => {
  formData.age = date
    ? Math.floor((Date.now() - new Date(date)) / (1000 * 60 * 60 * 24 * 365))
    : 0
})

// 加载列表
async function loadData() {
  const res = await axios.post(
    'CustomerController/queryAll',
    qs.stringify({
      cur: currentPage.value,
      number: pageSize.value,
      name: searchForm.name,
      type: searchForm.type
    })
  )
  const rb = res.data
  if (rb.status === 200) {
    tableData.value = rb.data
    total.value = rb.total
  } else {
    tableData.value = []
    total.value = 0
    ElMessage.warning('暂无数据')
  }
}

// 搜索
function searchData() {
  currentPage.value = 1
  loadData()
}

// 加载房间号
async function loadRooms() {
  const res = await axios.get('RoomInfoController/queryAllRoomNumber')
  if (res.data.status === 200) {
    rooms.value = res.data.data
  }
}

// 房间改变
async function onRoomChange(room) {
  const res = await axios.post(
    'BedInfoController/queryVacantBedNumberByRoomNumber',
    qs.stringify({ roomNumber: room })
  )
  if (res.data.status === 200) {
    bedData.value = res.data.data
  }
}

// 新增
function addData() {
  drawerTitle.value = '入住登记'
  drawerVisible.value = true
  Object.assign(formData, {
    id: 0,
    name: '',
    type: searchForm.type,
    birthDate: '',
    age: 0,
    gender: 0,
    idCardNumber: '',
    bloodType: 1,
    familyContact: '',
    building: '606',
    roomNumber: '',
    bedNumber: '',
    checkInTime: '',
    contractEndTime: '',
    isDeleted: false
  })
  loadRooms()
}

// 编辑
function editData(row) {
  drawerTitle.value = '修改入住'
  drawerVisible.value = true
  Object.assign(formData, row)
  loadRooms()
  onRoomChange(formData.roomNumber)
}

// 删除（逻辑删除并将床位状态改为空闲）
async function deleteData(id) {
  // 1. 逻辑删除客户
  await axios.post('CustomerController/deleteCustomer', qs.stringify({ id }))
  // 3. 把床位状态置为“空闲”（status=1）
  await axios.post(
    'BedInfoController/updateStatusByCustomer',
    qs.stringify({ customerId: id, status: 1 })
  )
  // 2. 把当前客户有效的床位使用详情也逻辑删除
  await axios.post(
    'BedAssignmentController/deleteByCustomer',
    qs.stringify({ customerId: id })
  )
  ElMessage.success('删除成功')
  loadData()
}

// 提交新增/修改
async function onSubmit() {
  formRef.value.validate(async valid => {
    if (!valid) return
    formData.birthDate = dayjs(formData.birthDate).format('YYYY-MM-DD HH:mm:ss')
    formData.checkInTime = dayjs(formData.checkInTime).format('YYYY-MM-DD HH:mm:ss')
    formData.contractEndTime = dayjs(formData.contractEndTime).format('YYYY-MM-DD HH:mm:ss')

    const api =
      drawerTitle.value === '入住登记'
        ? 'CustomerController/addCustomer'
        : 'CustomerController/updateCustomer'

    const res = await axios.post(api, qs.stringify(formData))
    if (res.data.status === 200) {
      // 新增时：在床位分配表插入一条记录 + 设置床位状态占用
      if (drawerTitle.value === '入住登记') {
        await axios.post(
          'BedAssignmentController/addBedAssignment',
          qs.stringify({
            customerId: res.data.data,
            bedNumber: formData.bedNumber, // 假设 bedNumber 存的是 bedInfoId
            assignStartTime: formData.checkInTime,
			assignEndTime: formData.contractEndTime,
            isDeleted: false
          })
        )
        await axios.post(
          'BedInfoController/updateStatusByBedNumber',
          qs.stringify({ bedNumber: formData.bedNumber, status: 2 }) // 2=有人
        )
      } else {
        // 修改时：若合同到期时间变更，更新当前床位使用详情的退住时间
        await axios.post(
          'BedAssignmentController/updateEndTimeByCustomer',
          qs.stringify({ customerId: formData.id, assignEndTime: formData.contractEndTime })
        )
      }

      ElMessage.success(drawerTitle.value + '成功')
      drawerVisible.value = false
      loadData()
    } else {
      ElMessage.error(drawerTitle.value + '失败：' + res.data.message)
    }
  })
}

// 初始加载
loadData()
</script>

<style scoped>
.el-form-item { margin-right: 16px; margin-bottom: 12px; }
.table-title { background-color: blue; color: #fff; padding: 8px; }
.el-pagination { margin-top: 20px; }
</style>
